package com.access.boot.apisdk;

import com.access.boot.apisdk.util.HandlerMethod;
import com.access.boot.apisdk.util.HandlerMethodUtils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author Yangzhen
 * @date 2023/1/9 16:19
 * @since 1.0.0
 */
public class SdkManager {

    private static final RequestResponseResolver REQUEST_RESPONSE_RESOLVER = new RequestResponseResolver();

    public static <T> T get(Class clazz) {

        HandlerMethodUtils.methodAnalysis(clazz);

        return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                if (args == null || args.length == 0) {
                    throw new IllegalArgumentException("没有SdkContext");
                }
                SdkContext sdkContext = null;
                boolean hasSdkContext = false;
                for (Object arg : args) {
                    if (arg instanceof SdkContext) {
                        hasSdkContext = true;
                        sdkContext = (SdkContext) arg;
                        break;
                    }
                }
                if (!hasSdkContext) {
                    throw new IllegalArgumentException("没有SdkContext");
                }
                HandlerMethod handlerMethod = HandlerMethodUtils.getHandlerMethod(method);
                return (T) REQUEST_RESPONSE_RESOLVER.doRequest(handlerMethod, sdkContext, args);
            }
        });
    }
}
